import { NextRequest, NextResponse } from 'next/server';
import { mockUsers } from '@/mock/users';
import { LoginRequest, LoginResponse, AuthUser } from '@/types/auth';
import { generateToken } from '@/utils/auth';

// 模拟用户凭据（实际项目中应该从数据库验证）
const userCredentials = [
  { username: 'admin', password: 'admin123' },
  { username: 'manager1', password: 'manager123' },
  { username: 'dev1', password: 'dev123' },
  { username: 'dev2', password: 'dev123' },
  { username: 'designer1', password: 'designer123' },
  { username: 'test1', password: 'test123' },
  { username: 'sales1', password: 'sales123' },
  { username: 'guest1', password: 'guest123' },
];

// 角色权限映射
const rolePermissions: Record<string, string[]> = {
  admin: [
    'user:read', 'user:create', 'user:update', 'user:delete',
    'ticket:read', 'ticket:create', 'ticket:update', 'ticket:delete',
    'system:read', 'system:update'
  ],
  manager: [
    'user:read', 'user:update',
    'ticket:read', 'ticket:create', 'ticket:update', 'ticket:delete'
  ],
  user: [
    'ticket:read', 'ticket:create', 'ticket:update'
  ],
  guest: [
    'ticket:read'
  ]
};

// POST /api/auth/login - 用户登录
export async function POST(request: NextRequest) {
  try {
    const body: LoginRequest = await request.json();
    const { username, password } = body;

    // 验证必填字段
    if (!username || !password) {
      return NextResponse.json(
        { success: false, message: '用户名和密码不能为空' },
        { status: 400 }
      );
    }

    // 验证用户凭据
    const credentials = userCredentials.find(
      cred => cred.username === username && cred.password === password
    );

    if (!credentials) {
      return NextResponse.json(
        { success: false, message: '用户名或密码错误' },
        { status: 401 }
      );
    }

    // 查找用户信息
    const user = mockUsers.find(u => u.username === username);
    if (!user) {
      return NextResponse.json(
        { success: false, message: '用户不存在' },
        { status: 404 }
      );
    }

    // 检查用户状态
    if (user.status !== 'active') {
      return NextResponse.json(
        { success: false, message: '用户账户已被禁用' },
        { status: 403 }
      );
    }

    // 构建认证用户信息
    const authUser: AuthUser = {
      id: user.id,
      username: user.username,
      email: user.email,
      displayName: user.displayName,
      avatar: user.avatar,
      role: user.role as any,
      permissions: rolePermissions[user.role] || [],
    };

    // 生成 token
    const token = generateToken(authUser);

    // 更新用户最后登录时间（在实际项目中应该更新数据库）
    const userIndex = mockUsers.findIndex(u => u.id === user.id);
    if (userIndex !== -1) {
      mockUsers[userIndex].lastLoginAt = new Date().toISOString();
    }

    const response: LoginResponse = {
      success: true,
      data: {
        token,
        user: authUser,
      },
      message: '登录成功',
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('登录失败:', error);
    return NextResponse.json(
      { success: false, message: '登录失败，请稍后重试' },
      { status: 500 }
    );
  }
} 